package com.gzyz.drug.controller;

import com.gzyz.drug.commmon.ResultMapUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @RequestMapping(value = "/login")
    public String login(){
        return "/login";
    }

    @RequestMapping(value = "/toLogin")
    @ResponseBody
    public Object toLogin(String username,String password,String code, HttpSession session){

        System.out.println(code);
        if (!StringUtils.hasLength(code)){
            return ResultMapUtil.getHashMapLogin("验证码不能为空","2");
        }
        String kaptchaCode = session.getAttribute("verifyCode")+"";
        if (!StringUtils.hasLength(kaptchaCode)||!code.toLowerCase().equals(kaptchaCode)){
            return ResultMapUtil.getHashMapLogin("验证码错误","2");
        }




        if (username==null||password==null){
            return ResultMapUtil.getHashMapLogin("用户名或密码不能为空","2");

        }
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username,password);
        try{
            subject.login(token);
        }catch (UnknownAccountException e){
            return ResultMapUtil.getHashMapLogin("用户名不存在","2");

        }catch (IncorrectCredentialsException e){
            return ResultMapUtil.getHashMapLogin("密码错误","2");

        }
        return ResultMapUtil.getHashMapLogin("验证成功","1");
    }

    @RequestMapping(value = "/index")
    public String index(){
        return "/index";
    }
    /**
     * 退出登录
     */
    @RequestMapping(value = "/logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/login";
    }
}
